//
//  HKMonthPicker.m
//  HKProject
//
//  Created by 胡锦涛 on 2018/8/14.
//  Copyright © 2018年 胡锦涛. All rights reserved.
//

#import "HKMonthPicker.h"

#ifdef NSCalendarUnitMonth
#define NSCalendarUnitMonth NSMonthCalendarUnit
#endif

#ifdef NSCalendarUnitYear
#define NSCalendarUnitYear NSYearCalendarUnit
#endif

#define kDatePicHeight 200
#define kTopViewHeight 44

#define SCREEN_BOUNDS [UIScreen mainScreen].bounds
#define HK_PICKER_WIDTH [UIScreen mainScreen].bounds.size.width
#define HK_PICKER_HEIGHT [UIScreen mainScreen].bounds.size.height

@interface HKBaseMonthPicker()

@property (nonatomic) NSInteger monthComponent;
@property (nonatomic) NSInteger yearComponent;
@property (nonatomic, strong, readonly) NSArray* monthStrings;
@property (nonatomic, strong, readonly) NSDateFormatter* monthFormatter;
@property (nonatomic, strong, readonly) NSDateFormatter* yearFormatter;

-(void)p_prepare;
-(NSInteger)p_yearFromRow:(NSUInteger)row;
-(NSUInteger)p_rowFromYear:(NSInteger)year;

@end

@implementation HKBaseMonthPicker

static const NSInteger HKMonthRowMultiplier = 340;
static const NSInteger HKDefaultMinimumYear = 1;
static const NSInteger HKDefaultMaximumYear = 99999;
static const NSCalendarUnit SRDateComponentFlags = NSCalendarUnitMonth | NSCalendarUnitYear;

- (id)initWithDate:(NSDate *)date calendar:(NSCalendar *)calendar
{
    self = [super init];
    
    if (self)
    {
        _calendar = calendar;
        [self p_prepare];
        [self setDate:date];
        self.showsSelectionIndicator = YES;
    }
    
    return self;
}

-(id)initWithDate:(NSDate *)date
{
    self = [self initWithDate:date calendar:[NSCalendar currentCalendar]];
    return self;
}

-(id)init
{
    self = [self initWithDate:[NSDate date] calendar:[NSCalendar currentCalendar]];
    return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    
    if (self)
    {
        _minimumYear = HKDefaultMinimumYear;
        _maximumYear = HKDefaultMaximumYear;
        [self p_prepare];
        if (!_calendar)
            _calendar = [NSCalendar currentCalendar];
        if (!_date) {
            [self setDate:[self hk_pastYear:3]];
        }
        
    }
    
    return self;
}

-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    
    if (self)
    {
        _minimumYear = HKDefaultMinimumYear;
        _maximumYear = HKDefaultMaximumYear;
        [self p_prepare];
        if (!_calendar)
            _calendar = [NSCalendar currentCalendar];
        if (!_date)
            [self setDate:[NSDate date]];
    }
    
    return self;
}

-(id<UIPickerViewDelegate>)delegate
{
    return self;
}

-(void)setDelegate:(id<UIPickerViewDelegate>)delegate
{
    if ([delegate isEqual:self])
        [super setDelegate:delegate];
}

-(id<UIPickerViewDataSource>)dataSource
{
    return self;
}

-(void)setDataSource:(id<UIPickerViewDataSource>)dataSource
{
    if ([dataSource isEqual:self])
        [super setDataSource:dataSource];
}

-(NSInteger)monthComponent
{
    return self.yearComponent ^ 1;
}

-(NSInteger)yearComponent
{
    return !self.yearFirst;
}

-(NSDateFormatter *)monthFormatter {
    static NSDateFormatter *formatter;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        formatter = [[NSDateFormatter alloc] init];
        NSLocale *zh_Locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh-Hans"];
        [formatter setLocale:zh_Locale];
        formatter.calendar = self.calendar;
        formatter.dateFormat = @"MMMM";
    });
    return formatter;
}

-(NSDateFormatter *)yearFormatter {
    static NSDateFormatter *formatter;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        formatter = [[NSDateFormatter alloc] init];
        NSLocale *zh_Locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh-Hans"];
        [formatter setLocale:zh_Locale];
        formatter.calendar = self.calendar;
        formatter.dateFormat = @"yyyy年";
    });
    return formatter;
}

-(NSArray *)monthStrings
{
    return self.monthFormatter.monthSymbols;
}

-(void)setYearFirst:(BOOL)yearFirst
{
    _yearFirst = yearFirst;
    self.date = [self hk_pastYear:3];
    [self reloadAllComponents];
    [self setNeedsLayout];
    [self setDate:self.date];
}

-(void)setMinimumYear:(NSInteger)minimumYear
{
    NSDate* currentDate = self.date;
    NSDateComponents* components = [self.calendar components:SRDateComponentFlags fromDate:currentDate];
    components.timeZone = [NSTimeZone defaultTimeZone];
    
    if (components.year < minimumYear)
        components.year = minimumYear;
    
    _minimumYear = minimumYear;
    [self reloadAllComponents];
    [self setDate:[self.calendar dateFromComponents:components]];
}

-(void)setMaximumYear:(NSInteger)maximumYear
{
    NSDate* currentDate = self.date;
    NSDateComponents* components = [self.calendar components:SRDateComponentFlags fromDate:currentDate];
    components.timeZone = [NSTimeZone defaultTimeZone];
    
    if (components.year > maximumYear)
        components.year = maximumYear;
    
    _maximumYear = maximumYear;
    [self reloadAllComponents];
    [self setDate:[self.calendar dateFromComponents:components]];
}

-(void)setWrapMonths:(BOOL)wrapMonths
{
    _wrapMonths = wrapMonths;
    [self reloadAllComponents];
}

-(void)setDate:(NSDate *)date
{
    NSDateComponents* components = [self.calendar components:SRDateComponentFlags fromDate:date];
    components.timeZone = [NSTimeZone defaultTimeZone];
    
    if (self.minimumYear && components.year < self.minimumYear)
        components.year = self.minimumYear;
    else if (self.maximumYear && components.year > self.maximumYear)
        components.year = self.maximumYear;
    
    if(self.wrapMonths) {
        NSInteger monthMidpoint = self.monthStrings.count * (HKMonthRowMultiplier / 2);
        
        [self selectRow:(components.month - 1 + monthMidpoint) inComponent:self.monthComponent animated:NO];
    } else
        [self selectRow:(components.month - 1) inComponent:self.monthComponent animated:NO];
    
    [self selectRow:[self p_rowFromYear:components.year] inComponent:self.yearComponent animated:NO];
    
    _date = [self.calendar dateFromComponents:components];
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSDateComponents* components = [[NSDateComponents alloc] init];
    components.month = 1 + ([self selectedRowInComponent:self.monthComponent] % self.monthStrings.count);
    components.year = [self p_yearFromRow:[self selectedRowInComponent:self.yearComponent]];
    
    [self willChangeValueForKey:@"date"];
//    if ([self.monthPickerDelegate respondsToSelector:@selector(monthPickerWillChangeDate:selectedConponents:)])
//        [self.monthPickerDelegate monthPickerWillChangeDate:self selectedConponents:components];
    
    _date = [self.calendar dateFromComponents:components];
    
    if ([self.monthPickerDelegate respondsToSelector:@selector(monthPickerDidChangeDate:selectedConponents:)])
        [self.monthPickerDelegate monthPickerDidChangeDate:self selectedConponents:components];
    [self didChangeValueForKey:@"date"];
}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == self.monthComponent && !self.wrapMonths)
        return self.monthStrings.count;
    else if(component == self.monthComponent)
        return HKMonthRowMultiplier * self.monthStrings.count;
    
    NSInteger maxYear = HKDefaultMaximumYear;
    if (self.maximumYear)
        maxYear = self.maximumYear;
    
    return [self p_rowFromYear:maxYear] + 1;
}

-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    if (component == self.monthComponent)
        return 200;
    else
        return 76.0f;
}

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    CGFloat width = [self pickerView:self widthForComponent:component];
    CGRect frame = CGRectMake(0.0f, 0.0f, width, 45.0f);
    
    if (component == self.monthComponent)
    {
        const CGFloat padding = 40;
        if (component) {
            frame.origin.x += padding;
            frame.size.width -= padding;
        }
    }
    frame.origin.x = 120;
    UILabel* label = [[UILabel alloc] initWithFrame:frame];
    
    NSDateFormatter* formatter = nil;
    if (component == self.monthComponent) {
        label.text = [self.monthStrings objectAtIndex:(row % self.monthStrings.count)];
        label.textAlignment = NSTextAlignmentRight;
        formatter = self.monthFormatter;
    } else {
        formatter = self.yearFormatter;
        label.text = [NSString stringWithFormat:@"%ld年", (long)[self p_yearFromRow:row]];
        label.textAlignment = NSTextAlignmentRight;
    }
    
    label.font = self.font;
    label.textColor = self.fontColour;
    
    if (self.enableColourRow && [[formatter stringFromDate:[NSDate date]] isEqualToString:label.text])
        label.textColor = self.selectedDateColor;
    
    label.shadowOffset = CGSizeMake(0.0f, 0.1f);
    label.shadowColor = [UIColor whiteColor];
    
    return label;
}
- (void)setSelectedDateColor:(UIColor *)selectedDateColor {
    _selectedDateColor = selectedDateColor;
}
#pragma mark Private Methods

-(NSInteger)p_yearFromRow:(NSUInteger)row
{
    NSInteger minYear = HKDefaultMinimumYear;
    
    if (self.minimumYear)
        minYear = self.minimumYear;
    
    return row + minYear;
}

-(NSUInteger)p_rowFromYear:(NSInteger)year
{
    NSInteger minYear = HKDefaultMinimumYear;
    
    if (self.minimumYear)
        minYear = self.minimumYear;
    
    return year - minYear;
}

-(void)p_prepare
{
    self.dataSource = self;
    self.delegate = self;
    
    self.enableColourRow = YES;
    self.wrapMonths = YES;
    
    self.font = [UIFont boldSystemFontOfSize:17];
    self.fontColor = [UIColor blackColor];
}

- (NSDate *)hk_pastYear:(NSInteger)pastYear {
    NSDate *currentDate = [NSDate date];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentDate];
    NSInteger m = [components month]; // month
    NSInteger d = [components day]; // day
    NSInteger y = [components year]; // year
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setDay:d];
    [comps setMonth:m];
    NSInteger resultYear = y-pastYear;
    [comps setYear:resultYear];
    NSCalendar *tempCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *date = [tempCalendar dateFromComponents:comps];
    NSLog(@"==========%@",date);
    return date;
}

@end
@interface HKMonthPicker()<HKMonthPickerDelegate>
@property (nonatomic, strong) NSString * title ;
@property (nonatomic, strong) NSString * minDateStr ;
@property (nonatomic, strong) NSString * maxDateStr ;
@property (nonatomic, strong) NSDateComponents* selectedComponents;
@property (nonatomic, assign) BOOL isAutoSelect;// 是否开启自动选择
@property (nonatomic, strong) HKBaseMonthPicker *datePicker;

@end
@implementation HKMonthPicker

#pragma mark - 初始化时间选择器
- (instancetype)initWithTitle:(NSString *)title defaultDate:(NSDate *)defaultDate minDateStr:(NSString *)minDateStr maxDateStr:(NSString *)maxDateStr isAutoSelect:(BOOL)isAutoSelect; {
    if (self = [super init]) {
        _title = title;
        _minDateStr = minDateStr;
        _maxDateStr = maxDateStr;
        _isAutoSelect = isAutoSelect;
        if (defaultDate != nil) {
            NSDate *currentDate = defaultDate;
            NSCalendar* calendar = [NSCalendar currentCalendar];
            NSDateComponents* components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentDate];
            self.selectedComponents = components;
        } else {
            // 不设置默认日期，就默认选中今天的日期
            NSDate *currentDate = [NSDate date];
            NSCalendar* calendar = [NSCalendar currentCalendar];
            NSDateComponents* components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentDate];
            self.selectedComponents = components;
        }
        [self initUI];
    }
    return self;
}

#pragma mark - 初始化子视图
- (void)initUI {
    [super initUI];
    self.titleLabel.text = _title;
    // 添加时间选择器
    [self.alertView addSubview:self.datePicker];
}

#pragma mark - 时间选择器
- (HKBaseMonthPicker *)datePicker {
    if (!_datePicker) {
        _datePicker = [[HKBaseMonthPicker alloc]initWithFrame:CGRectMake(0, self.alertView.frame.size.height-kDatePicHeight, HK_PICKER_WIDTH, kDatePicHeight)];
        _datePicker.backgroundColor = [UIColor whiteColor];
        _datePicker.monthPickerDelegate = self;
        //设置格式
        _datePicker.yearFirst = YES;
        // 设置时间范围
        if (_minDateStr) {
            _datePicker.minimumYear = [_minDateStr integerValue];
        }
        if (_maxDateStr) {
            _datePicker.maximumYear = [_maxDateStr integerValue];
        }
        _datePicker.fontColour = [UIColor redColor];
        //设置日期显示的common字体颜色
        _datePicker.fontColor = [UIColor blackColor];
        //设置选中时的颜色
        _datePicker.selectedDateColor = [UIColor blackColor];
        _datePicker.font = [UIFont systemFontOfSize:17];
    }
    return _datePicker;
}

#pragma mark - 背景视图的点击事件
- (void)didTapBackgroundView:(UITapGestureRecognizer *)sender {
    [self dismissWithAnimation:NO];
}

#pragma mark - 弹出视图方法
- (void)showWithAnimation:(BOOL)animation {
    //1. 获取当前应用的主窗口
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    [keyWindow addSubview:self];
}

#pragma mark - 关闭视图方法
- (void)dismissWithAnimation:(BOOL)animation {
    // 关闭动画
    [UIView animateWithDuration:0.2 animations:^{
        self.backgroundView.alpha = 0;
    } completion:^(BOOL finished) {
        [self.leftBtn removeFromSuperview];
        [self.rightBtn removeFromSuperview];
        [self.titleLabel removeFromSuperview];
        [self.lineView removeFromSuperview];
        [self.topView removeFromSuperview];
        [self.datePicker removeFromSuperview];
        [self.alertView removeFromSuperview];
        [self.backgroundView removeFromSuperview];
        [self removeFromSuperview];
        
        self.leftBtn = nil;
        self.rightBtn = nil;
        self.titleLabel = nil;
        self.lineView = nil;
        self.topView = nil;
        self.datePicker = nil;
        self.alertView = nil;
        self.backgroundView = nil;
    }];
}

#pragma mark - 取消按钮的点击事件
- (void)clickLeftBtn {
    [self dismissWithAnimation:YES];
}

#pragma mark - 确定按钮的点击事件
- (void)clickRightBtn {
    NSLog(@"点击确定按钮后，执行block回调");
    [self dismissWithAnimation:YES];
    if (self.onTap) {
        self.onTap(self.selectedComponents);
    }
    
}

#pragma mark---------HKMonthPickerDelegate------

- (void)monthPickerDidChangeDate:(HKMonthPicker *)monthPicker selectedConponents:(NSDateComponents *)selectedConponents {
    self.selectedComponents = selectedConponents;
}
@end
